<template>
  <ArticleMenu />
  <ArticleTopBg
    height="600px"
    v-motion
    :initial="{ opacity: 0, y: 50 }"
    :enter="{ opacity: 1, y: 0, transition: { duration: 800 } }"
  ></ArticleTopBg>
  <div class="friend-links-container">
    <!-- 本站信息卡片 -->
    <div class="site-info-card">
      <div class="card-header">
        <PhPushPin class="icon" />
        <h2>本站信息</h2>
      </div>
      <div class="info-content">
        <div class="info-item">
          <img :src="siteInfo.logo" alt="logo" class="site-logo">
          <div class="site-details">
            <h3>{{ siteInfo.name }}</h3>
            <p>{{ siteInfo.description }}</p>
            <a :href="siteInfo.url" target="_blank" class="site-url">
              <PhLink class="icon" />
              {{ siteInfo.url }}
            </a>
          </div>
          <button class="copy-all-btn" @click="copyAllInfo">
            <PhCopy class="icon" />
            一键复制
          </button>
        </div>
      </div>
    </div>

    <!-- 友链列表 -->
    <div class="links-section">
      <div class="section-header">
        <div class="tabs">
          <button
            v-for="category in categories"
            :key="category.value"
            :class="['tab-btn', { active: currentCategory === category.value }]"
            @click="currentCategory = category.value">
            {{ category.label }}
          </button>
        </div>
        <button class="apply-btn" @click="showApplyForm = true">
          <PhHandshake class="icon" />
          申请友链
        </button>
      </div>

      <div class="links-grid">
        <div v-for="link in filteredLinks"
             :key="link.id"
             class="link-card">
          <img :src="link.logo || defaultLogo" :alt="link.name" class="link-avatar">
          <div class="link-info">
            <h3>{{ link.name }}</h3>
            <p>{{ link.description }}</p>
            <a :href="link.url" target="_blank" class="visit-link">
              <PhArrowSquareOut class="icon" />
              访问
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 申请表单模态框 -->
    <Teleport to="body">
      <Transition name="fade">
        <div class="modal-overlay" v-if="showApplyForm" @click="showApplyForm = false">
          <div class="modal-content box-radius" @click.stop>
            <!-- 模态框头部 -->
            <div class="modal-header">
              <h3>申请友链</h3>
              <button class="close-btn" @click="showApplyForm = false">
                <PhX :size="20" weight="bold" />
              </button>
            </div>

            <!-- 模态框内容 -->
            <div class="modal-body">
              <form class="apply-form" @submit.prevent="submitApplication">
                <div class="form-item">
                  <input
                    v-model="formData.name"
                    type="text"
                    placeholder="网站名称"
                    :class="{ error: errors.name }"
                    @blur="validateField('name')"
                  >
                  <span v-if="errors.name" class="error-message">
                    {{ errors.name }}
                  </span>
                </div>

                <div class="form-item">
                  <input
                    v-model="formData.url"
                    type="url"
                    placeholder="网站链接（以 http(s):// 开头）"
                    :class="{ error: errors.url }"
                    @blur="validateField('url')"
                  >
                  <span v-if="errors.url" class="error-message">
                    {{ errors.url }}
                  </span>
                </div>

                <div class="form-item">
                  <input
                    v-model="formData.logo"
                    type="url"
                    placeholder="网站Logo链接"
                    :class="{ error: errors.logo }"
                    @blur="validateField('logo')"
                  >
                  <span v-if="errors.logo" class="error-message">
                    {{ errors.logo }}
                  </span>
                </div>

                <div class="form-item">
                  <textarea
                    v-model="formData.description"
                    placeholder="网站描述（不超过50字）"
                    maxlength="50"
                    :class="{ error: errors.description }"
                    @blur="validateField('description')"
                  ></textarea>
                  <span v-if="errors.description" class="error-message">
                    {{ errors.description }}
                  </span>
                </div>

                <div class="form-item">
                  <input
                    v-model="formData.email"
                    type="email"
                    placeholder="站长邮箱（选填）"
                    :class="{ error: errors.email }"
                    @blur="validateField('email')"
                  >
                  <span v-if="errors.email" class="error-message">
                    {{ errors.email }}
                  </span>
                </div>

                <div class="form-item">
                  <CustomSelect
                    v-model="formData.category"
                    :options="categories.slice(1)"
                    placeholder="请选择网站分类"
                    :error="!!errors.category"
                  />
                  <span v-if="errors.category" class="error-message">
                    {{ errors.category }}
                  </span>
                </div>

                <div class="form-tips">
                  <p>完善的友链信息有助于增加通过率</p>
                </div>

                <button type="submit" class="submit-btn" :disabled="isSubmitting">
                  {{ isSubmitting ? '提交中...' : '提交申请' }}
                </button>
              </form>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
  <LayoutFooter />
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, onMounted } from 'vue';
import type { FriendLink } from '@/types/links';
import { FriendLinkCategory, FriendLinkStatus } from '@/types/links';
import Message from '@/components/message';
import { applyFriendLink, getFriendLinks } from '@/api/links';
import {
  PhPushPin,
  PhLink,
  PhCopy,
  PhHandshake,
  PhArrowSquareOut,
  PhX
} from '@phosphor-icons/vue';
import CustomSelect from '@/components/custom-select.vue';
import ArticleMenu from '@/components/article-menu.vue';
import ArticleTopBg from '@/components/article-top-bg.vue';
import LayoutFooter from '@/components/layout-footer.vue';

// 本站信息
const siteInfo = {
  name: 'StarMist-小屋',
  url: 'https://starmist.net',
  description: '星辰与薄雾间，记录思考与生活的诗意栖居',
  logo: 'https://image.starmist.net/blog/article-cover/5b7c797c-f68d-4e49-ac88-c374bbce6b87.png'
};

// 默认logo
const defaultLogo = '/images/default-avatar.png';

// 分类列表
const categories = [
  { label: '全部', value: 'ALL' },
  { label: '技术博客', value: FriendLinkCategory.TECHNOLOGY },
  { label: '生活博客', value: FriendLinkCategory.LIFE },
  { label: '资源网站', value: FriendLinkCategory.RESOURCE },
  { label: '其他', value: FriendLinkCategory.OTHER }
];

const currentCategory = ref('ALL');
const friendLinks = ref<FriendLink[]>([]);
const showApplyForm = ref(false);
const isSubmitting = ref(false);

// 表单数据
const formData = reactive({
  name: '',
  url: '',
  logo: '',
  description: '',
  email: '',
  category: ''
});

// 错误状态
const errors = reactive({
  name: '',
  url: '',
  logo: '',
  description: '',
  email: '',
  category: ''
});

// 根据分类筛选友链
const filteredLinks = computed(() => {
  if (currentCategory.value === 'ALL') {
    return friendLinks.value;
  }
  return friendLinks.value.filter(
    link => link.category === currentCategory.value
  );
});

// 获取友链列表
const loadFriendLinks = async () => {
  try {
    const res = await getFriendLinks();
    friendLinks.value = res.data;
  } catch (error) {
    Message.error('获取友链列表失败');
  }
};

// 复制本站信息
const copyAllInfo = async () => {
  const info = `
    网站名称：${siteInfo.name}
    网站链接：${siteInfo.url}
    网站描述：${siteInfo.description}
    网站Logo：${siteInfo.logo}
  `.trim();

  try {
    await navigator.clipboard.writeText(info);
    Message.success('复制成功');
  } catch (err) {
    Message.error('复制失败，请手动复制');
  }
};

// 表单验证
const validateField = (field: keyof typeof formData) => {
  switch (field) {
  case 'name':
    if (!formData.name.trim()) {
      errors.name = '请输入网站名称';
    } else if (formData.name.length > 30) {
      errors.name = '网站名称不能超过30个字符';
    } else {
      errors.name = '';
    }
    break;
  case 'url':
    if (!formData.url.trim()) {
      errors.url = '请输入网站链接';
    } else if (!/^https?:\/\/.+/.test(formData.url)) {
      errors.url = '请输入有效的网站链接';
    } else {
      errors.url = '';
    }
    break;
  case 'logo':
    if (formData.logo && !/^https?:\/\/.+/.test(formData.logo)) {
      errors.logo = '请输入有效的图片链接';
    } else {
      errors.logo = '';
    }
    break;
  case 'description':
    if (!formData.description.trim()) {
      errors.description = '请输入网站描述';
    } else if (formData.description.length > 50) {
      errors.description = '描述不能超过50字';
    } else {
      errors.description = '';
    }
    break;
  case 'category':
    if (!formData.category) {
      errors.category = '请选择网站分类';
    } else {
      errors.category = '';
    }
    break;
  }
};

// 监听表单字段变化
watch(formData, (newVal, oldVal) => {
  Object.keys(newVal).forEach(key => {
    if (newVal[key as keyof typeof formData] !== oldVal[key as keyof typeof formData]) {
      validateField(key as keyof typeof formData);
    }
  });
}, { deep: true });

// 提交友链申请
const submitApplication = async () => {
  if (isSubmitting.value) return;

  // 验证所有字段
  Object.keys(formData).forEach(key => {
    validateField(key as keyof typeof formData);
  });

  // 检查是否有错误
  if (Object.values(errors).some(error => error !== '')) {
    return;
  }

  try {
    isSubmitting.value = true;
    await applyFriendLink(formData);
    Message.success('申请提交成功，请等待审核');
    showApplyForm.value = false;
    // 重置表单
    Object.keys(formData).forEach(key => {
      formData[key as keyof typeof formData] = '';
    });
    // 重置错误状态
    Object.keys(errors).forEach(key => {
      errors[key as keyof typeof errors] = '';
    });
  } catch (error: any) {
    Message.error(error.response?.data?.message || '提交申请失败');
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(() => {
  loadFriendLinks();
});
</script>
<style lang="less" scoped>
.friend-links-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;

  .icon {
    width: 1.2em;
    height: 1.2em;
  }
}

.site-info-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 40px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;

    .icon {
      width: 1.5em;
      height: 1.5em;
      color: #60a5fa;
    }

    h2 {
      font-size: 1.5rem;
      color: #1f2937;
      margin: 0;
    }
  }

  .info-content {
    .info-item {
      display: flex;
      align-items: center;
      gap: 24px;

      .site-logo {
        width: 80px;
        height: 80px;
        border-radius: 12px;
        object-fit: cover;
      }

      .site-details {
        flex: 1;

        h3 {
          margin: 0 0 8px;
          color: #1f2937;
        }

        p {
          color: #6b7280;
          margin: 0 0 12px;
        }

        .site-url {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #60a5fa;
          text-decoration: none;
          font-size: 0.9rem;

          &:hover {
            text-decoration: underline;
          }
        }
      }

      .copy-all-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        border-radius: 8px;
        border: none;
        background: #60a5fa;
        color: white;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background: #3b82f6;
          transform: translateY(-1px);
        }

        .icon {
          width: 1.1em;
          height: 1.1em;
        }
      }
    }
  }
}

.links-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .tabs {
      display: flex;
      gap: 12px;
      overflow-x: auto;
      padding-bottom: 4px;

      .tab-btn {
        padding: 8px 16px;
        border: none;
        border-radius: 8px;
        background: #f3f4f6;
        color: #4b5563;
        cursor: pointer;
        transition: all 0.3s ease;
        white-space: nowrap;

        &:hover {
          background: #e5e7eb;
        }

        &.active {
          background: #60a5fa;
          color: white;
        }
      }
    }

    .apply-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      border: none;
      border-radius: 8px;
      background: #10b981;
      color: white;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: #059669;
        transform: translateY(-1px);
      }

      .icon {
        width: 1.1em;
        height: 1.1em;
      }
    }
  }

  .links-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 24px;

    .link-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      gap: 16px;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px -2px rgba(0, 0, 0, 0.15);
      }

      .link-avatar {
        width: 64px;
        height: 64px;
        border-radius: 8px;
        object-fit: cover;
      }

      .link-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        h3 {
          margin: 0 0 8px;
          color: #1f2937;
          font-size: 1.1rem;
        }

        p {
          margin: 0 0 12px;
          color: #6b7280;
          font-size: 0.9rem;
          line-height: 1.4;
          flex: 1;
        }

        .visit-link {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #60a5fa;
          text-decoration: none;
          font-size: 0.9rem;
          width: fit-content;

          &:hover {
            text-decoration: underline;
          }

          .icon {
            width: 1.1em;
            height: 1.1em;
          }
        }
      }
    }
  }
}

.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }

  .close-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border: none;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    transition: all 0.2s;

    &:hover {
      background: #f1f5f9;
      color: #1f2937;
    }
  }
}

.modal-body {
  padding: 24px;
}

.apply-form {
  .form-item {
    margin-bottom: 24px;
    position: relative;

    input, textarea {
      width: 100%;
      box-sizing: border-box;
      padding: 12px 16px;
      border: 1px solid #e2e8f0;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.2s;
      background: white;
      color: #1f2937;

      &::placeholder {
        color: #9ca3af;
      }

      &:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &.error {
        border-color: #ef4444;

        &:focus {
          box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
      }
    }

    textarea {
      min-height: 100px;
      resize: vertical;
    }

    .error-message {
      position: absolute;
      left: 0;
      bottom: -20px;
      font-size: 12px;
      color: #ef4444;
      display: flex;
      align-items: center;
      gap: 4px;
      opacity: 0;
      transform: translateY(-5px);
      animation: slideIn 0.3s ease forwards;
    }
  }

  .form-tips {
    padding: 12px;
    background: #f8fafc;
    border-radius: 8px;
    margin-bottom: 24px;

    p {
      margin: 0;
      font-size: 13px;
      color: #64748b;
    }
  }

  .submit-btn {
    width: 100%;
    padding: 12px;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    &:hover:not(:disabled) {
      background: #2563eb;
    }

    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
}

// 动画
@keyframes slideIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 深色模式
@media (prefers-color-scheme: dark) {
  .site-info-card,
  .link-card {
    background: #1f2937;

    .card-header h2,
    .site-details h3 {
      color: #e5e7eb;
    }

    .site-details p {
      color: #9ca3af;
    }
  }

  .links-section {
    .section-header .tabs .tab-btn {
      background: #374151;
      color: #9ca3af;

      &:hover {
        background: #4b5563;
      }
    }
  }

  .modal-content {
    background: #1f2937;
  }

  .modal-header {
    border-bottom-color: #374151;

    h3 {
      color: #e5e7eb;
    }

    .close-btn {
      color: #9ca3af;

      &:hover {
        background: #374151;
        color: #e5e7eb;
      }
    }
  }

  .apply-form {
    .form-item {
      input, textarea {
        background: #374151;
        border-color: #4b5563;
        color: #e5e7eb;

        &::placeholder {
          color: #9ca3af;
        }

        &:hover {
          border-color: #6b7280;
        }

        &:focus {
          border-color: #60a5fa;
          box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
        }

        &.error {
          border-color: #f87171;

          &:focus {
            box-shadow: 0 0 0 3px rgba(248, 113, 113, 0.1);
          }
        }
      }
    }

    .form-tips {
      background: #374151;

      p {
        color: #9ca3af;
      }
    }
  }
}

// 响应式布局
@media (max-width: 768px) {
  .friend-links-container {
    padding: 20px;
  }

  .site-info-card {
    .info-content {
      .info-item {
        flex-direction: column;
        text-align: center;
        gap: 16px;

        .site-details {
          text-align: center;

          .site-url {
            justify-content: center;
          }
        }
      }
    }
  }

  .links-section {
    .section-header {
      flex-direction: column;
      gap: 16px;

      .tabs {
        width: 100%;
        justify-content: flex-start;
      }

      .apply-btn {
        width: 100%;
        justify-content: center;
      }
    }
  }

  .links-grid {
    grid-template-columns: 1fr !important;
  }
}
</style>
